Skip to main content
ICT
Lesson A3 - Primitive Data Types
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

I. Increment and Decrement Operators page 11 of 14

  1. Incrementing or decrementing by one is a common task in programs. This task can be accomplished by the statements:

    n = n + 1;    or   n += 1;

  2. Java also provides a unary operator called an increment operator, ++.

  3. The statement n = n + 1 can be rewritten as ++n. The following statements are equivalent:

    n = n + 1; ++n;
    sum = sum + 1; ++sum;
  4. Java also provides for a decrement operator, --, which decrements a value by one. The following are equivalent statements:

    n = n - 1; --n;
    sum = sum - 1; --sum;
  5. The increment and decrement operators can be written as either a prefix or postfix unary operator. If the ++ is placed before the variable it is called a pre-increment operator (++number), but it can follow after the variable (number++), which is called a post-increment operator. The following three statements have the same effect:

    ++number;    number++;    number = number + 1;

  6. Before looking at the difference between prefix and postfix unary operators, it is important to remember Java operators solve problems and often return values. Just as the assignment operator (=) returns a value, the ++ and -- operators return values. Consider the following code fragments:

  7. The statement b = ++a uses the pre-increment operator. It increments the value of a and returns the new value of a.

  8. The statement b = a++ uses the post-increment operator. It returns the value of a and then increments a by 1.

  9. The precedence and associativity of the unary increment and decrement operators is the same as the unary - operator.

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.